package com.kob.backend.controller.user.account;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kob.backend.pojo.DueHistroy;
import com.kob.backend.pojo.Seat;
import com.kob.backend.pojo.SeatRecord;
import com.kob.backend.service.user.DueHistoryService;
import com.kob.backend.service.user.SeatRecordService;
import com.kob.backend.service.user.account.SeatStatusService;
import com.kob.backend.utils.DateTimeUtils;
import com.kob.backend.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController

public class SeatStatusController {
    @Autowired
    private SeatStatusService seatstatusService;
    @Autowired
    private SeatRecordService seatRecordService;
    private int Getseatid = 1;
    @Autowired
    private DueHistoryService dueHistoryService;
    @Autowired
    private DateTimeUtils dateTimeUtils;

    private final List<String> allTimeSlots = new ArrayList<String>() {{
        add("07:00~09:00");
        add("09:10~11:10");
        add("11:20~13:20");
        add("13:30~15:30");
        add("15:40~17:40");
        add("17:50~19:50");
        add("20:00~23:00");
    }};

    /**
     * 预约
     */
    @PostMapping("user/account/seatDue/")
    @CrossOrigin(origins = "http://localhost:8080") // 允许跨域请求从指定源
    public Map<String, String> seatDue(@RequestParam int labelId, @RequestParam int seatId, @RequestParam String selectedDateSlot, @RequestParam String selectedTimeSlot, HttpServletRequest request) {
        //检查token
        String token = request.getHeader("Authorization");
        if (null == token || token.trim().isEmpty()) {
            Map<String, String> result = new HashMap<>();
            result.put("result", "error");
            result.put("message", "token没传");
            return result;
        }
        //检查是否已被预约
        String userid = JwtUtil.extractUsername(token.replace("Bearer","").trim());
        //一个用户某个时间段只能预约一个座位
        boolean useExist = seatRecordService.userHasDue(userid, selectedDateSlot, selectedTimeSlot);
        if (useExist) {
            Map<String, String> result = new HashMap<>();
            result.put("result", "error");
            result.put("message", "所选时间段您已成功预约了一个座位,无需再次预约");
            return result;
        }
        //一个座位某个时间段只能被预约一次
        boolean seatExist = seatRecordService.seatHasDue(seatId, selectedDateSlot, selectedTimeSlot);
        if (seatExist) {
            Map<String, String> result = new HashMap<>();
            result.put("result", "error");
            result.put("message", "该座位在所选时间段已被预约");
            return result;
        }
        //保存预约
        SeatRecord data = new SeatRecord();
        data.setUser(userid);
        data.setSeatId(seatId);
        data.setDateSlot(selectedDateSlot);
        data.setTimeSlot(selectedTimeSlot);
        data.setLabelId(labelId);
        // 往历史记录表存的信息  // 每预约一次，就存一次，不管是否又取消，先存
        DueHistroy histroy = new DueHistroy();
        histroy.setUserid(userid);
        histroy.setDate(selectedDateSlot);
        histroy.setTime(selectedTimeSlot);
        histroy.setSeatid(seatId);
        histroy.setDuetime(dateTimeUtils.getCurrentDateTime());  // 获取当前系统时间
        int res2 = dueHistoryService.save(histroy);

        int res = seatRecordService.save(data);
        if (res == 1) {
            Map<String, String> result = new HashMap<>();
            result.put("result", "success");
            result.put("message", "预约成功");
            return result;
        } else {
            Map<String, String> result = new HashMap<>();
            result.put("result", "error");
            result.put("message", "保存数据库时出错,请稍后再试");
            return result;
        }
        /*
        System.out.println("Selected Time Slot: " + selectedTimeSlot);
        System.out.println("选择的座位id: " + seatId);
        Getseatid = seatId;
        return seatstatusService.seatstatus(seatId, selectedTimeSlot);
        */
    }

    /**
     * 取消预约
     */
    @DeleteMapping("user/account/seatUnDue/")
    @CrossOrigin(origins = "http://localhost:8080") // 允许跨域请求从指定源
    public Map<String, String> seatUnDue(@RequestParam int seatId, @RequestParam String selectedDateSlot, @RequestParam String selectedTimeSlot, HttpServletRequest request) {
        //检查token
        String token = request.getHeader("Authorization");
        if (null == token || token.trim().isEmpty()) {
            Map<String, String> result = new HashMap<>();
            result.put("result", "error");
            result.put("message", "token没传");
            return result;
        }
        String userid = JwtUtil.extractUsername(token.replace("Bearer","").trim());

        // 检查是否已经进行签到
        boolean isSigned = dueHistoryService.seatHasSignIn(seatId, userid, selectedDateSlot, selectedTimeSlot);
        if(isSigned) {
            System.out.println("已经签到, 不能再取消预约");
            Map<String, String> result = new HashMap<>();
            result.put("result", "error");
            result.put("message", "已签到，不能取消预约");
            return result;
        }

        //检查是否已被预约
        boolean exist = seatRecordService.seatUserHasDue(seatId, userid, selectedDateSlot, selectedTimeSlot);
        if (!exist) {
            Map<String, String> result = new HashMap<>();
            result.put("result", "error");
            result.put("message", "非本人预约,不能取消预约");
            return result;
        }

        /*取消预约标记,设置duehistory表记录为1*/
        DueHistroy histroy = new DueHistroy();
        histroy.setUserid(userid);
        histroy.setDate(selectedDateSlot);
        histroy.setTime(selectedTimeSlot);
        int ret = dueHistoryService.setCancel(histroy);


        SeatRecord data = new SeatRecord();
        data.setSeatId(seatId);
        data.setDateSlot(selectedDateSlot);
        data.setTimeSlot(selectedTimeSlot);
        // 只有删除这个表里面的这条记录，才会更新签到页面的座位图标
        // 才相当于取消预约
        int res = seatRecordService.delete(data);  // 取消预约后会将seatrecord表中的对应记录删除，但是历史记录表中会有该条记录
        if (res == 1) {
            Map<String, String> result = new HashMap<>();
            result.put("result", "success");
            result.put("message", "预约取消成功");
            return result;
        } else {
            Map<String, String> result = new HashMap<>();
            result.put("result", "error");
            result.put("message", "取消预约时数据库出错,请稍后再试");
            return result;
        }
    }

    /**
     * 获取座位最新的预约状态
     */
    @PostMapping("user/account/getseatstatus/")
    @CrossOrigin(origins = "http://localhost:8080") // 允许跨域请求从指定源
    public List<Map<Integer, Boolean>> getSeatId(@RequestParam String selectedDateSlot, @RequestParam String selectedTimeSlot) {
        List<Map<Integer, Boolean>> result = new ArrayList<>();
        //所有的座位
        List<Seat> allSeat = seatstatusService.getAllSeat();
        for (Seat seat : allSeat) {
            int seatId = seat.getId();
            //查询是否已被预约
            boolean hasDue = seatRecordService.seatHasDue(seatId, selectedDateSlot, selectedTimeSlot);
            Map<Integer, Boolean> item = new HashMap<>();
            item.put(seatId, hasDue);
            result.add(item);
        }
        return result;
        /*
        List<Integer> list = new ArrayList<>();
        for (int i = 1; i <= 25; i++) {
            int status = seatstatusService.getstatus(i);
            list.add(status);
        }
        return list;
        */
    }


    /*
     * 签到功能
     * 前端进行判断：时间段开始前后10分钟，允许签到
     * 参数：座位号，日期，时间段
     * 后端根据传入的这三个参数遍历duehistory表，将对应那栏记录的issignin字段设置为true
     * 签到后，不允许再进行取消预约操作
     * 返回值：成功或失败
     */
    @PostMapping("user/account/signin/")
    @CrossOrigin(origins = "http://localhost:8080") // 允许跨域请求从指定源
    public Map<String, String> signin(@RequestParam int seatId, @RequestParam String selectedDateSlot, @RequestParam String selectedTimeSlot, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (null == token || token.trim().isEmpty()) {
            Map<String, String> result = new HashMap<>();
            result.put("result", "error");
            result.put("message", "token没传");
            return result;
        }
        // 获取用户id
        String userid = JwtUtil.extractUsername(token.replace("Bearer","").trim());
        System.out.println(userid +" " + seatId + " " + selectedDateSlot + " " + selectedTimeSlot);

        DueHistroy dueHistroy = new DueHistroy();
        dueHistroy.setUserid(userid);
        dueHistroy.setSeatid(seatId);
        dueHistroy.setDate(selectedDateSlot);
        dueHistroy.setTime(selectedTimeSlot);

        // 将该条记录的issignin字段设置为1
        int res = dueHistoryService.setSignin(dueHistroy);
        if(res == 1)
        {
            Map<String, String> result = new HashMap<>();
            result.put("result", "success");
            result.put("message", "签到成功");
            return result;
        }
        else {
            Map<String, String> result = new HashMap<>();
            result.put("result", "error");
            result.put("message", "请检查该条记录信息是否正确");
            return result;
        }
    }
}
